from django.http import HttpRequest
from django.utils import timezone
from pinject import new_object_graph

from common.auth_utils import login_required
from common.errors import InvalidParameter
from common.http_utils import SuccessResponse
from common.request_utils import get_request_data, request_parameter_check
from content_center import forms
from content_center.application.service import ContentService
from content_center.infrastructure import adapter, repository
from content_center.models import Content, SportLabel, UniversityLabel, Comment


def get_contents(request: HttpRequest):
    form = request_parameter_check(
        get_request_data(request), form_class=forms.GetContentForm
    )
    obj_graph = new_object_graph(modules=[adapter, repository])
    service = obj_graph.provide(ContentService)
    return SuccessResponse(service.get_contents(**form.data))


@login_required
def create_contents(request: HttpRequest):
    form = request_parameter_check(
        get_request_data(request), form_class=forms.CreateContentForm
    )
    data = form.data
    university_label_ids = data.pop("university_label_ids")
    sport_label_ids = data.pop("sport_label_ids")
    obj_graph = new_object_graph(modules=[adapter, repository])
    service = obj_graph.provide(ContentService)
    service.create_content(
        request.user.id, university_label_ids, sport_label_ids, **data
    )
    return SuccessResponse("创建成功!")


@login_required
def edit_contents(request: HttpRequest):
    form = request_parameter_check(
        get_request_data(request), form_class=forms.EditContentForm
    )
    data = form.data
    university_label_ids = data.pop("university_label_ids")
    sport_label_ids = data.pop("sport_label_ids")
    content_id = data.pop("content_id")
    obj_graph = new_object_graph(modules=[adapter, repository])
    service = obj_graph.provide(ContentService)
    service.edit_content(content_id, university_label_ids, sport_label_ids, **data)
    return SuccessResponse("修改成功!")


@login_required
def delete_contents(request: HttpRequest):
    content_id = request.GET.get("content_id")
    if not content_id:
        raise InvalidParameter("参数错误！")
    content = Content.objects.filter(id=content_id, is_deleted=False).first()
    if not content:
        raise InvalidParameter("该文章不存在！")
    content.is_deleted = True
    content.update_time = timezone.now()
    content.save()
    return SuccessResponse("删除成功！")


def get_labels(request):
    university_labels = UniversityLabel.objects.all()
    sport_labels = SportLabel.objects.all()
    return SuccessResponse(
        {
            "university_labels": [
                {
                    "id": university_label.id,
                    "university_name": university_label.university_name,
                }
                for university_label in university_labels
            ],
            "sport_labels": [
                {"id": sport_label.id, "sport_name": sport_label.sport_name}
                for sport_label in sport_labels
            ],
        }
    )


def get_comments(request):
    form = request_parameter_check(
        get_request_data(request), form_class=forms.GetCommentForm
    )
    content_id = form.cleaned_data["content_id"]
    page_size = form.cleaned_data["page_size"]
    page_no = form.cleaned_data["page_no"]
    offset = (page_no - 1) * page_size
    comments = Comment.objects.filter(user_id=content_id, content_id=content_id).select_related("user")
    total = comments.count()
    comments = comments[offset: offset + page_size]
    return SuccessResponse(
        {"total": total, "comments": [{"id": comment.id, "text": comment.text, "username": comment.user.username,
                                       "avatar": comment.user.avatar,
                                       "create_time": comment.create_time.strftime("%Y-%m-%d %D:%M:%S")} for comment in
                                      list(comments)]})
